<template>
    <div class="e-form">
        <BillTop title="操作手汇总详情" @cancel="handleClose"></BillTop>
        <div class="tabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="考核记录" name="records" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="工作经历" name="workExperience" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="证书信息" name="information" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                            <div style="width: 100%" class="form">
                                <el-form ref="form" :model="formData.operator" label-width="200px">
                                    <el-row>
                                        <el-col :span="12">
                                        <el-form-item label="来源：">
                                                <span>{{ ['外部','内部'][formData.operator.source] }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="姓名：">
                                                <span>{{ formData.operator.operator }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="联系电话：">
                                                <span>{{ formData.operator.phoneNo }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="身份证号：">
                                                <span>{{ formData.operator.idCard }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="性别：">
                                                <span>{{ ['女','男'][formData.operator.gender] }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="工作状态：">
                                                <span>{{ getLabel(formData.operator) }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="入场时间：">
                                                <span>{{ formData.operator.enterDate }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="离场时间：">
                                                <span>{{ formData.operator.exitDate }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="等级机构：">
                                                <span>{{ formData.operator.orgName}}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="操作范围：">
                                                <span> {{ formData.operator.operatingRange }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </div>
                    </div>

                    <div id="recordsCon" class="con">
                        <div class="tabs-title" id="records">考核记录</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                :data="formData.operatorAssessment"
                                border
                                ref="records"
                                v-sortTable="{ 'tableData': formData.operatorAssessment, '_this': this, 'ref': 'records' }"
                            >
                                <el-table-column
                                    prop="assessmentContent"
                                    align="center"
                                    min-width="200"
                                    show-overflow-tooltip
                                    label="考评内容"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="assessmentLevel"
                                    label="考评等级"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ assessmentLevel[row.assessmentLevel] }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="操作机构"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="recorder"
                                    label="操作人"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="workExperienceCon" class="con">
                        <div class="tabs-title" id="workExperience">工作经历</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                :data="formData.operatorWorkExperience"
                                border
                                ref="workExperience"
                                v-sortTable="{ 'tableData': formData.operatorWorkExperience, '_this': this, 'ref': 'workExperience' }"
                            >
                                <el-table-column
                                    prop="corporateName"
                                    label="单位名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="operatingRange"
                                    label="操作范围"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="startDate"
                                    label="开始时间"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="endDate"
                                    label="结束时间"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <!-- <el-table-column
                                    prop="source"
                                    label="来源"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{['系统外','系统内'][row.source] }}</span>
                                    </template>
                                </el-table-column> -->
                            </el-table>
                        </div>
                    </div>

                    <div id="informationCon" class="con">
                        <div class="tabs-title" id="information">证书信息</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button class="btn-greenYellow" @click="attachDownload">批量下载</el-button>
                                    </div>
                                </div>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="information"
                                :data="formData.operatorCertificate"
                                @selection-change="fileTableSelect"
                                border
                                v-sortTable="{ 'tableData': formData.operatorCertificate, '_this': this, 'ref': 'information' }"
                            >
                                <el-table-column type="selection" align="center" width="55"></el-table-column>
                                <el-table-column
                                    prop="operatingRange"
                                    label="操作范围"
                                    min-width="160"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="certificationAuthority"
                                    label="发证机关"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="issueDate"
                                    label="发证日期"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="annualReview"
                                    label="年审日期"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column show-overflow-tooltip prop="filePath" width="200" label="缩略图">
                                    <template slot-scope="{ row }" :size="50">
                                        <div style="display: flex; justify-content: center;">
                                            <!-- <el-image
                                                v-if="'jpg,jpeg,png'.includes(row.fileName.split('.').pop().toLowerCase())"
                                                style="width: 60px; height: 60px"
                                                :src="row.filePath"
                                                :preview-src-list="[row.filePath]"
                                            ></el-image> -->
                                            <el-image
                                                v-if="'jpg,jpeg,png'.includes(row.objectName.split('.').pop().toLowerCase())"
                                                style="width: 30px; height: 30px"
                                                :src="oss + row.nonIPObjectPath"
                                                :preview-src-list="imageList"
                                            ></el-image>
                                            <el-image v-else style="width: 60px; height: 60px" :src="pdfImg"></el-image>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="fileName"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                    label="文件名称"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="fileSize"
                                    label="文件大小"
                                    width="100"
                                    align="center"
                                >
                                    <!-- <template slot-scope="{ row }">
                                        {{ row.fileSize ? bytesToSize(row.fileSize) : '' }}
                                    </template> -->
                                </el-table-column>
                                <el-table-column
                                    prop="uploaderDate"
                                    label="上传时间"
                                    show-overflow-tooltip
                                    width="120"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="uploader"
                                    label="上传人"
                                    width="120"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="uploader"
                                    label="状态"
                                    width="120"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button size="small" class="btn-blue"  v-debounce>打印</el-button>
            <el-button size="small" @click="handleClose"  v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/operatorManagement.js'
import '@/utils/jquery.scrollTo.min'
import service from '@/utils/request'
import { batchDownload } from '@/utils/common'
import { oss } from '@/utils/request'
export default {
    data () {
        return {
            oss: oss,
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            selectEquipVisible: false,
            tableData: [],
            formData: {
                'operator': {
                    'assessmentContent': '',
                    'assessmentLevel': '',
                    'billId': '',
                    'enterDate': '',
                    'exitDate': '',
                    'founderId': '',
                    'founderName': '',
                    'gender': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'idCard': '',
                    'initial': '',
                    'isShared': true,
                    'isSynchronize': true,
                    'operatingRange': '',
                    'operator': '',
                    'orgId': '',
                    'orgName': '',
                    'phoneNo': '',
                    'recorder': '',
                    'recorderId': '',
                    'source': 0,
                    'workState': null
                },
                'operatorAssessment': [], //考核记录
                'operatorCertificate': [], //证书信息
                'operatorWorkExperience': [], //工作经历
                'state': 1
            },
            billid: this.$route.query.billid,
            fileSelect: [], //证书信息选择项
            asterisk: '', //星号
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            workStatus: state=>state.equip.equipData.workStatus,
            assessmentLevel: state=>state.equip.equipData.assessmentLevel,
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
    },
    created () {
        this.getInfo()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'records', 'workExperience', 'information']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })

    },
    methods: {
        //获取操作手信息
        getInfo () {
            try {
                request.operatorInfo(this.billid).then(res=>{
                    this.formData = res
                    this.formData.operator.idCard = this.hiddenCardID(this.formData.operator.idCard, 3, 4)
                })
            } catch (error) {
                alert(error.message)
            }
        },
        //隐藏身份证
        hiddenCardID (CardID, startLen, endLen) {
            let len = CardID.length - startLen - endLen
            for(let i = 0 ;i < len ; i++) {
                this.asterisk += '*'
            }
            return CardID.substring(0, startLen) + this.asterisk + CardID.substring(0, endLen)
        },
        //证书信息选中的行
        fileTableSelect (selection) {
            this.fileSelect = selection
        },
        //批量下载证书信息
        handledownload () {
            if(this.fileSelect.length === 0) {
                this.clientPop('err', '请选择下载的数据！')
                return
            }
            const promiseArr = []
            this.fileSelect.forEach(item => {
                promiseArr.push(this.downloadFile(item))
            })
            Promise.all(promiseArr).catch(err=>{
                alert(err.message)
            })
        },
        autoClick ({ fileName, url }) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = url
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
        },
        dataURLtoBlob (dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = window.atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        },
        downloadIamge (imgsrc, fileName) {
            //下载图片地址和图片名
            var image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function () {
                const canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                const context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                const _dataURL = canvas.toDataURL('image/png') //得到图片的base64编码数据

                const blob_ = this.dataURLtoBlob(_dataURL) // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会
                const url = {
                    name: fileName || '图片.png', // 图片名称不需要加.png后缀名
                    src: blob_
                }

                if (window.navigator.msSaveOrOpenBlob) {   // if browser is IE
                    navigator.msSaveBlob(url.src, url.name)//filename文件名包括扩展名，下载路径为浏览器默认路径
                } else {
                    this.autoClick({
                        fileName: url.name,
                        url: window.URL.createObjectURL(url.src)
                    })
                }
            }.bind(this)
            image.src = imgsrc
        },
        async downloadFile (obj) {
            const url = obj.filePath
            const fileNameFull = obj.fileName
            const fileExt = fileNameFull.split('.').pop()
            if (['jpg', 'jpeg', 'gif', 'png', 'bmp'].indexOf(fileExt.toLowerCase()) === -1) {
                const { httpGetFile } = service
                const data = await httpGetFile({ url })
                const blob = new Blob([data])
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = function (e) {
                    this.autoClick({
                        fileName: fileNameFull,
                        url: e.target.result
                    })
                }.bind(this)
            } else {
                this.downloadIamge(url, fileNameFull)
            }
        },
        //批量下载
        attachDownload () {
            const length = this.fileSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '请选择要下载的数据！',
                )
                return
            }
            const fileList = this.fileSelect.map(item=>{
                return {
                    objectName: item.fileName,
                    objectPath: item.filePath
                }
            })
            batchDownload(fileList)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //取消
        handleClose () {
            this.$router.replace('/operatorPoolList')
        },
        getLabel (row) {
            const findObj = this.workStatus.find(x=>Number(x.value) === row.workState)
            return findObj ? findObj.label : ''
        }
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}

</style>
